package dongze.com.ckdj.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

/**
 * Created by renxiaoxiao on 2017/8/10.
 */

public class TableView extends TableLayout {

    public TableView(Context context) {
        super(context);
    }

    public TableView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        // 创建画笔
        Paint mPaint = new Paint();
        // 设置画笔的各个属性
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(1);
        mPaint.setAntiAlias(true);

        // 获取布局控件宽高
        int width = getWidth();
        int height = getHeight();
        // 画整个表格的边框线
        canvas.drawLine(0, 0, width, 0, mPaint);
        canvas.drawLine(0, height, width, height, mPaint);
        canvas.drawLine(0, 0, 0, height, mPaint);

        // 有数据的情况下
        if (getChildAt(0) instanceof TableRow) {
            TableRow row = (TableRow) getChildAt(0);
            int count = row.getChildCount();
            int drawX = 0;
            for(int i = 0; i < count; i++) {
                TextView textView = (TextView) row.getChildAt(i);
                int textWidth = textView.getWidth();
                int left = textView.getLeft();
                drawX = (left + textWidth / 2 - drawX) * 2 + drawX;
                canvas.drawLine(drawX, 0, drawX, height, mPaint);
            }

            // 画每行的底边框
            for (int i = 0; i < getChildCount(); i++) {
                if (i != getChildCount() - 1)
                    canvas.drawLine(0, row.getHeight() * (i + 1), width, row.getHeight() * (i + 1), mPaint);
            }
        }

        // 最后必须调用父类的方法
        super.dispatchDraw(canvas);
    }
}
